package smarthome

import "fmt"

// ========= 调用者：遥控器 =========
type RemoteControl struct {
	onCommands  []Command
	offCommands []Command
	history     []Command // 命令历史记录
}

func NewRemoteControl() *RemoteControl {
	return &RemoteControl{
		onCommands:  make([]Command, 5), // 5个插槽
		offCommands: make([]Command, 5),
		history:     make([]Command, 0, 100),
	}
}

func (r *RemoteControl) SetCommand(slot int, onCommand, offCommand Command) {
	if slot >= 0 && slot < len(r.onCommands) {
		r.onCommands[slot] = onCommand
		r.offCommands[slot] = offCommand
	}
}

func (r *RemoteControl) PressOnButton(slot int) {
	if slot >= 0 && slot < len(r.onCommands) && r.onCommands[slot] != nil {
		r.onCommands[slot].Execute()
		r.history = append(r.history, r.onCommands[slot])
	}
}

func (r *RemoteControl) PressOffButton(slot int) {
	if slot >= 0 && slot < len(r.offCommands) && r.offCommands[slot] != nil {
		r.offCommands[slot].Execute()
		r.history = append(r.history, r.offCommands[slot])
	}
}

func (r *RemoteControl) PressButton(cmd Command) {
	cmd.Execute()
	r.history = append(r.history, cmd)
}

func (r *RemoteControl) UndoLast() {
	if len(r.history) > 0 {
		lastCmd := r.history[len(r.history)-1]
		fmt.Printf("撤销上一个命令: %s\n", lastCmd.GetName())
		lastCmd.Undo()
		r.history = r.history[:len(r.history)-1] // 移除最后一个命令
	} else {
		fmt.Println("没有可以撤销的命令")
	}
}

func (r *RemoteControl) ShowHistory() {
	fmt.Println("\n===== 命令历史记录 =====")
	for i, cmd := range r.history {
		fmt.Printf("%d. %s\n", i+1, cmd.GetName())
	}
}
